package marvin.webapp.audio.rtp;

import java.io.*;
import java.net.URI;
import java.util.List;
//import javax.media.format.AudioFormat;

import marvin.webapp.audio.subscription.ClientHandler;
import marvin.webapp.audio.util.PushNotifier;
import marvin.webapp.exception.MarvinException;

public class RTPServer {

	private static final String CMD_STOP = "cmd:stop";
	private static final String CMD_SUSPEND = "cmd:suspend";
	private static final String CMD_RESUME = "cmd:resume";

	private List<File> files;
	private int fileIndex = 0;
	private ClientHandler clientHandler;
	private String currentStreamedFile;
	private boolean repeating, shuffle;
	
	public RTPServer(String dstAddress, int dstPort, int basePort, ClientHandler clientHandler){
		this.clientHandler = clientHandler;
	}
	
	public void streamFiles(List<File> files) throws IOException, MarvinException{
		this.files = files; 
		fileIndex = -1;
		playNext();
	}
	
	private void computeNextIndex(){
		if(!shuffle){
			if(fileIndex < files.size() - 1)
				fileIndex ++;
			else{
				if (repeating){
					fileIndex = 0;
				}
			}
				
		} else {
			fileIndex = (int) (Math.random() * files.size());
		}
	}
	
	public void playNext() throws IOException, MarvinException {
		if(files != null){
			
			computeNextIndex();
			
			stopStreaming();
				
			if(files != null && files.size() > fileIndex)
				streamFile(files.get(fileIndex));
		}
	}
	
	public void playPrevious() throws IOException, MarvinException {
		if(files != null){
			if(fileIndex > 0)
				fileIndex --;
			stopStreaming();
				
			if(files != null && fileIndex > 0)
				streamFile(files.get(fileIndex));
		}
	}
	
	private void streamFile(File file){
		clientHandler.sentToClient("file:"+file.getAbsolutePath());
		clientHandler.setCurrentFilePath(file.getAbsolutePath());
		PushNotifier.sendNotification("Streamed file", file.getAbsolutePath());
	}
	
	public void stopStreaming(){
		if(clientHandler.getCurrentFilePath() != null && !clientHandler.getCurrentFilePath().isEmpty()){
			clientHandler.sentToClient(CMD_STOP);
			clientHandler.setCurrentFilePath(null);
		}
	}
	
	public void suspendStreaming(){
		clientHandler.sentToClient(CMD_SUSPEND);
	}
	
	public void resumeStreaming(){
		clientHandler.sentToClient(CMD_RESUME);
	}

	public String getCurrentStreamedFile() {
		return currentStreamedFile;
	}

	public boolean getRepeatMode() {
		return repeating;
	}
	
	public void setRepeatMode(boolean mode) {
		repeating = mode;
	}

	public boolean isShuffle() {
		return shuffle;
	}

	public void setShuffle(boolean shuffle) {
		this.shuffle = shuffle;
	}

	public void stream(URI uri) {
		clientHandler.setCurrentFilePath(uri.getPath());
		clientHandler.sentToClient("web:"+"http:"+uri.getPath());
	}
}

